package org.zuel.boot.demo.controller;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zuel.boot.demo.exception.BizException;
import org.zuel.boot.demo.model.DemoUser;
import org.zuel.boot.demo.service.IUserService;
import org.zuel.boot.demo.util.ResponseUtil;

@RestController
@RequestMapping(value = "/user")
public class UserController {
    private final IUserService userService;

    @Autowired
    public UserController(IUserService userService){
        this.userService=userService;
    }

    @PostMapping(value = "/regist")
    public Object regist(@RequestBody DemoUser model) {
        try {
            return userService.regist(model);
        } catch (BizException e) {
            return ResponseUtil.fail(e.getCode(), e.getMessage());
        }
    }

    @PostMapping(value = "/login")
    public Object login(@RequestBody DemoUser user) {
        try {
            return userService.login(user);
        } catch (BizException e) {
            return ResponseUtil.fail(e.getCode(), e.getMessage());
        }
    }

    @GetMapping(value = "/list")
    public Object list(@RequestParam(name = "username", required = false) String username,
                       @RequestParam(name = "nickname", required = false) String nickname,
                       @RequestParam(name = "sex", required = false) Integer sex,
                       @RequestParam(name = "con", required = false) String con,
                       @RequestParam(name = "page", defaultValue = "1", required = false) Integer page,
                       @RequestParam(name = "limit", defaultValue = "10", required = false) Integer limit,
                       @RequestParam(name = "sort", defaultValue = "add_time", required = false) String sort,
                       @RequestParam(name = "order", defaultValue = "desc", required = false) String order) {
        return userService.list(username, nickname, sex, con, page, limit, sort, order);
    }

    @GetMapping(value = "/read/{id}")
    public Object read(@PathVariable("id") Integer id) {
        return userService.read(id);
    }
    @PostMapping(value = "/login2")
    public Object login2(@RequestBody DemoUser user) {
        return userService.login2(user);
    }

    @GetMapping(value = "/logout")
    public Object logout() {
        return userService.logout();
    }

    @RequiresAuthentication
    @GetMapping(value = "/showMe")
    public Object showMe() {
        return ResponseUtil.ok(userService.showMe());
    }

}
